package com.chinasoft.shiro.realms;

import com.chinasoft.shiro.realms.salt.MyByteSource;
import com.chinasoft.user.domain.User;
import com.chinasoft.user.service.UserService;
import com.chinasoft.utils.ApplicationContextUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.CollectionUtils;

/**
 * 自定义realm
 */
public class CustomerRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用授权方法了");
        //获取主身份信息
        String primaryPrincipal = (String)principalCollection.getPrimaryPrincipal();
        //在工厂中获取service对象
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");

        User user = userService.findRolesByAccount(primaryPrincipal);
        System.out.println("经过授权方法查询出来的用户信息"+user);
        //授权角色信息
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getRname());
                System.out.println(role.getRname());
            });
            return simpleAuthorizationInfo;
        }

        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用认证的方法了");
        String principal = (String)authenticationToken.getPrincipal();

        //在工厂中获取service对象
        UserService userService = (UserService)ApplicationContextUtils.getBean("userService");
        User user = userService.findByAccount(principal);
        System.out.println(user);
        if(user != null){
//            因为ByteSource类没有实现Serializable接口，不能序列化，所以要使用字节写的能序列化的MyByteSource
//            return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
            return new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(), new MyByteSource(user.getSalt()),this.getName());
        }

        return null;
    }
}
